﻿# -*- coding:utf-8 -*-
#
# Профиль пользователя
#
from django.shortcuts import render_to_response
from django.template import RequestContext, Context
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from userprofile.forms import ChangePassForm

def render_to(request, template, context):
    context_extra = Context({

    })
    return render_to_response(template, context, context_instance=RequestContext(request, context_extra))


def index(request): 
    context = Context({
    })
    return render_to(request, 'userprofile/index.html', context)


def change_password(request): 
    if request.method == 'POST':
        form = ChangePassForm(request.POST)
        if form.is_valid():
            user = User.objects.get(id = request.user.id)
            old_pass = form.cleaned_data['old_password']
            password = form.cleaned_data['password']
            password_repeat = form.cleaned_data['password_repeat']
            if user.check_password(old_pass):
                if password == password_repeat:
                    user.set_password(password)
                    user.save()
                else:
                    request.user.message_set.create(message="<font color='red'>Новые пароли не совпадают.</font>")
                    return HttpResponseRedirect(reverse('change_password'))
            else:
                request.user.message_set.create(message="<font color='red'>Ваш пароль неверен.</font>")
                return HttpResponseRedirect(reverse('change_password'))
            request.user.message_set.create(message="<font color='green'>Пароль успешно изменен.</font>")    
            return HttpResponseRedirect(reverse('userprofile_index')) 
    else:
        form = ChangePassForm()

    context = Context({
    'form': form,
    })
    return render_to(request, 'userprofile/change_password.html', context)